﻿/* ------------------------------------------------------------------------
* 【本类功能概述】
* 
* 创建人：
* 创建时间：2014/6/25 12:01:57
* 创建说明：
*
* 修改人： 
* 修改时间： 
* 修改说明：
* ------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Configuration;
using System.Web;
using MS.Utility.Common;
using MS.Enums.Common;
using MS.Utility.Config;

namespace MS.Utility.Logging
{
    public abstract class LogHelper
    {
        //static ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static ILog logger = LogManager.GetLogger("MSLoger");

        #region 操作日志 - 通用
        /// <summary>
        /// 操作日志 - 通用
        /// </summary>
        /// <param name="targetID"></param>
        /// <param name="actionInfo"></param>
        public static void Operate(string targetID, string actionInfo)
        {
            System.Reflection.MethodBase methodInfo = new System.Diagnostics.StackFrame(1).GetMethod();

            if (logger.IsInfoEnabled)
            {
                LogMessage cpm = new LogMessage
                {
                    ApplicationID = Convert.ToInt32(ConfigurationManager.AppSettings["ApplicationID"]),
                    ModuleName = methodInfo.DeclaringType.FullName,
                    MethodName = methodInfo.Name,
                    TargetID = targetID,
                    Action = actionInfo,
                    LoginName = GetLoginUid().ToString(),
                    CreateTime = DateTime.Now,
                    ServerName = UserHelper.GetServerName(),
                    ClientIP = UserHelper.GetUserIp(),
                    PageUrl = UserHelper.GetRequestUrl(),
                    OrganizationID = UserHelper.GetOrganizationID(),
                    ActionType = 0,
                    ReferrerUrl = UserHelper.GetRequestUrlReferrerAbsoluteUri()
                };
                logger.Info(cpm);
            }
        }
        #endregion

        #region 操作日志-增加数据
        /// <summary>
        /// 操作日志-增加数据
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="entity">数据实体</param>
        public static void AddOperate<T>(string targetID, T entity)
        {
            System.Reflection.MethodBase methodInfo = new System.Diagnostics.StackFrame(1).GetMethod();

            if (logger.IsInfoEnabled)
            {
                LogMessage cpm = new LogMessage
                {
                    ApplicationID = Convert.ToInt32(ConfigurationManager.AppSettings["ApplicationID"]),
                    ModuleName = methodInfo.DeclaringType.FullName,
                    MethodName = methodInfo.Name,
                    TargetID = targetID,
                    Action = string.Format("添加操作：\r\n {0}", JsonConvert.SerializeObject(entity)),
                    LoginName = GetLoginUid().ToString(),
                    CreateTime = DateTime.Now,
                    ServerName = UserHelper.GetServerName(),
                    ClientIP = UserHelper.GetUserIp(),
                    PageUrl = UserHelper.GetRequestUrl(),
                    OrganizationID = UserHelper.GetOrganizationID(),
                    ActionType = 0,
                    ReferrerUrl = UserHelper.GetRequestUrlReferrerAbsoluteUri()
                };
                logger.Info(cpm);
            }
        }
        #endregion

        #region 操作日志 - 更新数据
        public static void UpdateOperate<T>(string targetID, T oldEntity, T newEntity)
        {
            System.Reflection.MethodBase methodInfo = new System.Diagnostics.StackFrame(1).GetMethod();

            if (logger.IsInfoEnabled)
            {
                LogMessage cpm = new LogMessage
                {
                    ApplicationID = Convert.ToInt32(ConfigurationManager.AppSettings["ApplicationID"]),
                    ModuleName = methodInfo.DeclaringType.FullName,
                    MethodName = methodInfo.Name,
                    TargetID = targetID,
                    Action = string.Format("更新数据：\r\n原始数据：\r\n {0} \r\n更新数据：\r\n {1}", JsonConvert.SerializeObject(oldEntity), JsonConvert.SerializeObject(newEntity)),
                    LoginName = GetLoginUid().ToString(),
                    CreateTime = DateTime.Now,
                    ServerName = UserHelper.GetServerName(),
                    ClientIP = UserHelper.GetUserIp(),
                    PageUrl = UserHelper.GetRequestUrl(),
                    OrganizationID = UserHelper.GetOrganizationID(),
                    ActionType = 0,
                    ReferrerUrl = UserHelper.GetRequestUrlReferrerAbsoluteUri()
                };
                logger.Info(cpm);
            }
        }
        #endregion

        #region 操作日志-删除数据
        /// <summary>
        /// 操作日志-删除数据
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="entity">数据实体</param>
        public static void DeleteOperate<T>(string targetID, T entity)
        {
            System.Reflection.MethodBase methodInfo = new System.Diagnostics.StackFrame(1).GetMethod();

            if (logger.IsInfoEnabled)
            {
                LogMessage cpm = new LogMessage
                {
                    ApplicationID = Convert.ToInt32(ConfigurationManager.AppSettings["ApplicationID"]),
                    ModuleName = methodInfo.DeclaringType.FullName,
                    MethodName = methodInfo.Name,
                    TargetID = targetID,
                    Action = string.Format("删除操作：\r\n {0}", JsonConvert.SerializeObject(entity)),
                    LoginName = GetLoginUid().ToString(),
                    CreateTime = DateTime.Now,
                    ServerName = UserHelper.GetServerName(),
                    ClientIP = UserHelper.GetUserIp(),
                    PageUrl = UserHelper.GetRequestUrl(),
                    OrganizationID = UserHelper.GetOrganizationID(),
                    ActionType = 0,
                    ReferrerUrl = UserHelper.GetRequestUrlReferrerAbsoluteUri()
                };
                logger.Info(cpm);
            }
        }
        #endregion

        #region 错误日志
        public static void Error(Exception ex)
        {
            if (ex == null)
            {
                return;
            }
            Exception exInner = ex.InnerException;
            Exception exBase = ex.GetBaseException();

            if (exInner is System.Reflection.TargetInvocationException)//如果是：目标调用发生异常，取内部异常
            {
                if (exInner.InnerException != null)
                {
                    exInner = exInner.InnerException;
                }
            }
            /*
             *  为了保证所有的异常都显示最终消息，内部消息则记录数据库。
             *  例如：有些出错信息不应该提供给用户，但日志需要详细记录。
             *        则通过页面捕获异常后，包装此异常到新异常（新异常描述：系统出错！）内部，然后抛出。
             * */
            string msg = exInner != null ? exInner.Message : ex.Message;
            System.Reflection.MethodBase methodInfo = new System.Diagnostics.StackFrame(1).GetMethod();
            LogMessage errLog = new LogMessage()
            {
                ApplicationID = Convert.ToInt32(ConfigurationManager.AppSettings["ApplicationID"]),
                Message = exBase.Message,
                Function = methodInfo.DeclaringType.FullName + "." + methodInfo.Name,
                StackTrace = exBase.StackTrace,
                LoginName = GetLoginUid().ToString(),
                CreateTime = DateTime.Now,
                ServerName = UserHelper.GetServerName(),
                ClientIP = UserHelper.GetUserIp(),
                PageUrl = UserHelper.GetRequestUrl(),
                ActionType = 1,
                ReferrerUrl = UserHelper.GetRequestUrlReferrerAbsoluteUri()
            };
            //记录错误日志
            if (logger.IsErrorEnabled)
            {
                logger.Error(errLog);
            }
        }
        #endregion


        /// <summary>
        /// 获取登录的用户Uid，如果Uid为0代变未登录
        /// </summary>
        /// <param name="platform"></param>
        /// <returns></returns>
        public static long GetLoginUid(Platform platform = Platform.BMS)
        {
            long nLoginUid = 0;
            string key = GetLoginCookieKeyByPlatform(platform);
            string EncryptKey = ConfigSetting.EncryptKey;
            try
            {
                switch (platform)
                {
                    case Platform.BMS:

                        HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(key);
                        if (cookie != null)
                        {
                            string o = Utils.AESDecrypt(cookie.Value, EncryptKey);

                            UserModel model = JsonConvert.DeserializeObject<UserModel>(o);
                            nLoginUid = model.uid;

                        }

                        break;
                }
            }
            catch
            {

            }
            return nLoginUid;
        }
        /// <summary>
        /// 获取Cookie中记录用户登录token的Key值
        /// </summary>
        /// <param name="platform"></param>
        /// <returns></returns>
        private static string GetLoginCookieKeyByPlatform(Platform platform)
        {
            string key = "";
            switch (platform)
            {
                case Platform.BMS:
                    key = "bmsusertoken";
                    break;
            }
            return key;
        }
    }
    public class UserModel
    {
        public long uid { get; set; }
        public long time { get; set; }

    }
}
